﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Linq;

namespace UI_PMQLThuPhi_LMD
{
    public partial class FormQuanLyKhachHang : DevExpress.XtraEditors.XtraForm
    {
        DataClasses1DataContext dc = new DataClasses1DataContext();

        bool them = true;
        Khach_Hang kh;

        public FormQuanLyKhachHang()
        {
            InitializeComponent();
        }
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.F5)
            {
                btMaKhachHang_Click(null, EventArgs.Empty);
                return true;
            }
            else
            {
                return base.ProcessCmdKey(ref msg, keyData);
            }
            
        }

        private string CreateMaKhachHang()
        {
            string MaKhachHang = "";

            var qh = (from q in dc.Quan_Huyens where q.QH_ID == (int)cbbQuanHuyen.EditValue select q).Single();
            var px = (from p in dc.Phuong_Xas where p.PX_ID == (int)cbbPhuongXa.EditValue select p).Single();
            var kv = (from k in dc.Khu_Vucs where k.KV_ID == (int)cbbKhuVuc.EditValue select k).Single();
            var td = (from d in dc.Duongs where d.D_ID == (int)cbbTuyenDuong.EditValue select d).Single();

            return MaKhachHang = qh.QH_Ma + "_" + px.PX_Ma + "_" + kv.KV_Ma + "_" + td.D_Ma + "_" + txtSoNha.Text;
        }
        private void FillSource2LookUpEdit(LookUpEdit cbb, object source, string DisplayM, string ValueM)
        {
            cbb.Properties.DataSource = source;
            cbb.Properties.DisplayMember = DisplayM;
            cbb.Properties.ValueMember = ValueM;
        }
        private void ClearThongTin()
        {
            txtSoNha.Text = "";
            cbbTTLoaiKH.EditValue = null;
            txtSoLuong.Text = "";
            txtHoTen.Text = "";
            txtDienThoai.Text = "";
            cbbKyHan.EditValue = null;
            cbbTrangThai.EditValue = null;
            cbbNhanVien.EditValue = null;
            txtMaKhachHang.Text = "";

            dxErrorHoTen.ClearErrors();
            dxErrorKhuVuc.ClearErrors();
            dxErrorKyHan.ClearErrors();
            dxErrorMaKhachHang.ClearErrors();
            dxErrorPhuongXa.ClearErrors();
            dxErrorQuanHuyen.ClearErrors();
            dxErrorSoLuong.ClearErrors();
            dxErrorSoNha.ClearErrors();
            dxErrorTrangThai.ClearErrors();
            dxErrorTTLoaiKH.ClearErrors();
            dxErrorTuyenDuong.ClearErrors();
        }
        private void GridViewDSKH_Load()
        {
            //Gridview_Load
            if (TestDiaChi())
            {
                //Load dữ liệu lên gridview và repository trong gv
                var khs = from kh in dc.Khach_Hangs
                          where kh.KH_KVID == (int)cbbKhuVuc.EditValue &&
                              kh.KH_DID == (int)cbbTuyenDuong.EditValue
                          select kh;
                gcDanhSachKhachHang.DataSource = khs;

                var lkhs = from lkh in dc.Loai_Khach_Hangs select lkh;
                cbbLoaiKH.DataSource = lkhs;
                cbbLoaiKH.DisplayMember = "L_TenLoai";
                cbbLoaiKH.ValueMember = "L_ID";

                var nvs = from nv in dc.Nhan_Viens select nv;
                cbbKH_NVID.DataSource = nvs;
                cbbKH_NVID.DisplayMember = "NV_Ten";
                cbbKH_NVID.ValueMember = "NV_ID";

                txtSoNha.Focus();
            }
        }

        //Get Source Danh Muc
        #region

        private Object QuanHuyen()
        {
            var source = dc.GetTable<Quan_Huyen>();
            return source;
        }

        private Object PhuongXa()
        {
            if (cbbQuanHuyen.EditValue != null)
            {
                var source = from px in dc.Phuong_Xas where px.PX_QHID == (int)cbbQuanHuyen.EditValue select px;
                return source;
            }
            else
            {
                return null;
            }
        }

        private Object KhuVuc()
        {
            if (cbbPhuongXa.EditValue != null)
            {
                var source = from kv in dc.Khu_Vucs where kv.KV_PID == (int)cbbPhuongXa.EditValue select kv;
                return source;
            }
            else
            {
                return null;
            }
            
        }

        private Object Duong()
        {
            var source = dc.GetTable<Duong>();
            return source;
        }

        private Object LoaiKhachHang()
        {
            var source = dc.GetTable<Loai_Khach_Hang>();
            return source;
        }

        private Object KyHanNop()
        {
            var source = dc.GetTable<Ky_Han_Nop>();
            return source;
        }

        private Object TrangThai()
        {
            var source = dc.GetTable<Trang_Thai_Hoat_Dong>();
            return source;
        }

        private Object NhanVien()
        {
            var source = dc.GetTable<Nhan_Vien>();
            return source;
        }
        #endregion

        //Điều hướng
        #region
        private void cbbQuanHuyen_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                cbbPhuongXa.Focus();
            }
        }

        private void cbbPhuongXa_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                cbbKhuVuc.Focus();
            }
        }

        private void cbbKhuVuc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                cbbTuyenDuong.Focus();
            }
        }

        private void cbbTuyenDuong_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btXem.Focus(); //-->btXem -->txtSoNha
            }
        }
  
        private void txtSoNha_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btMaKhachHang_Click(null, EventArgs.Empty);
                txtHoTen.Focus();
            }
        }

        private void txtHoTen_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                cbbTTLoaiKH.Focus();
            }
        }

        private void cbbTTLoaiKH_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtSoLuong.Focus();
            }
        }

        private void txtSoLuong_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtDienThoai.Focus();
            }
        }

        private void txtDienThoai_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                cbbKyHan.Focus();
            }
        }

        private void cbbKyHan_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                cbbTrangThai.Focus();
            }
        }

        private void cbbTrangThai_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                cbbNhanVien.Focus();
            }
        }

        private void cbbNhanVien_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btLuu.Focus(); //-->btLuu -->cbbTTLoaiKH
            }
            else if (e.KeyCode == Keys.Delete)
            {
                cbbNhanVien.EditValue = null;
            }
        }

        #endregion

        //cbb EditValueChanged
        #region
        private void cbbQuanHuyen_EditValueChanged(object sender, EventArgs e)
        {
            if (cbbQuanHuyen.EditValue != null)
            {
                dxErrorQuanHuyen.ClearErrors();
            }
            FillSource2LookUpEdit(cbbPhuongXa, PhuongXa(), "PX_Ten", "PX_ID");
            cbbKhuVuc.EditValue = null;
            cbbPhuongXa.EditValue = null;
        }

        private void cbbPhuongXa_EditValueChanged(object sender, EventArgs e)
        {
            if (cbbPhuongXa.EditValue != null)
            {
                dxErrorPhuongXa.ClearErrors();
            }
            FillSource2LookUpEdit(cbbKhuVuc, KhuVuc(), "KV_Ten", "KV_ID");
            cbbKhuVuc.EditValue = null;
            
        }


        private void cbbTTLoaiKH_EditValueChanged(object sender, EventArgs e)
        {
            if (cbbTTLoaiKH.EditValue != null)
            {
                dxErrorTTLoaiKH.ClearErrors();
            }
            txtSoLuong.Text = "1";
        }
        #endregion

        //Test
        #region
        private Boolean TestDiaChi()
        {
            Boolean rs = true;
            if (cbbQuanHuyen.EditValue == null)
            {
                rs = false;
                dxErrorQuanHuyen.SetError(cbbQuanHuyen, "Vui lòng chọn quận huyện.");
            }
            else
            {
                dxErrorQuanHuyen.ClearErrors();
            }
            

            if (cbbPhuongXa.EditValue == null)
            {
                rs = false;
                dxErrorPhuongXa.SetError(cbbPhuongXa, "Vui lòng chọn phường xã.");
            }
            else
            {
                dxErrorPhuongXa.ClearErrors();
            }
            

            if (cbbKhuVuc.EditValue == null)
            {
                rs = false;
                dxErrorKhuVuc.SetError(cbbKhuVuc, "Vui lòng chọn khu vực.");
            }
            else
            {
                dxErrorKhuVuc.ClearErrors();
            }
            

            if (cbbTuyenDuong.EditValue == null)
            {
                rs = false;
                dxErrorTuyenDuong.SetError(cbbTuyenDuong, "Vui lòng chọn tuyến đường.");
            }
            else
            {
                dxErrorTuyenDuong.ClearErrors();
            }
           
            
           
            return rs;
        }

        private Boolean TestSoNha()
        {
            Boolean rs = true;
            if (txtSoNha.Text == "")
            {
                rs = false;
                dxErrorSoNha.SetError(txtSoNha, "Vui lòng điền số nhà.");
            }
            else
            {
                dxErrorSoNha.ClearErrors();
            }
            return rs;
        }

        private Boolean TestThongTinCaNhan()
        {
            Boolean rs = true;
            if (txtSoNha.Text == "")
            {
                rs = false;
                dxErrorSoNha.SetError(txtSoNha, "Vui lòng điền số nhà.");
            }
            else
            {
                dxErrorSoNha.ClearErrors();
            }

            if (txtHoTen.Text == "")
            {
                rs = false;
                dxErrorHoTen.SetError(txtHoTen, "Vui lòng điền họ tên.");
            }
            else
            {
                dxErrorHoTen.ClearErrors();
            }

            if (cbbTTLoaiKH.EditValue == null)
            {
                rs = false;
                dxErrorTTLoaiKH.SetError(cbbTTLoaiKH, "Vui lòng chọn loại khách hàng.");
            }
            else
            {
                dxErrorTTLoaiKH.ClearErrors();
            }

            if (txtSoLuong.Text == "")
            {
                rs = false;
                dxErrorSoLuong.SetError(txtSoLuong, "Vui lòng nhập số lượng.");
            }
            else
            {
                dxErrorSoLuong.ClearErrors();
            }

            if (cbbKyHan.EditValue == null)
            {
                rs = false;
                dxErrorKyHan.SetError(cbbKyHan, "Vui lòng chọn kỳ hạn.");
            }
            else
            {
                dxErrorKyHan.ClearErrors();
            }

            if (cbbTrangThai.EditValue == null)
            {
                rs = false;
                dxErrorTrangThai.SetError(cbbTrangThai, "Vui lòng chọn kỳ hạn.");
            }
            else
            {
                dxErrorTrangThai.ClearErrors();
            }
            return rs;
        }

        private Boolean TestMaKhachHang()
        {
            bool rs = true;
            if (CreateMaKhachHang() != txtMaKhachHang.Text)
            {
                rs = false;
                dxErrorMaKhachHang.SetError(txtMaKhachHang, "Mã khách hàng không hợp lệ");
            }
            else
            {
                dxErrorMaKhachHang.ClearErrors();
            }
            return rs;
        }

        private void cbbKhuVuc_EditValueChanged(object sender, EventArgs e)
        {
            if (cbbKhuVuc.EditValue != null)
            {
                dxErrorKhuVuc.ClearErrors();
            }
        }

        private void cbbTuyenDuong_EditValueChanged(object sender, EventArgs e)
        {
            if (cbbTuyenDuong.EditValue != null)
            {
                dxErrorTuyenDuong.ClearErrors();
            }
        }

        private void txtHoTen_EditValueChanged(object sender, EventArgs e)
        {
            if (txtHoTen.Text != "")
            {
                dxErrorHoTen.ClearErrors();
            }
        }

        #endregion        
        
        //sự kiện hỗ trợ
        #region
        private void btMaKhachHang_Click(object sender, EventArgs e)
        {
            bool test1 = TestDiaChi();
            bool test2 = TestSoNha();

            if (test1 && test2)
            {
                txtMaKhachHang.Text = CreateMaKhachHang();
            }
            else
            {
                txtMaKhachHang.Text = "";
            }
        }
        private void gvDanhSachKhachHang_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.Column == colSTT)
            {
                if (e.RowHandle >= 0)
                {
                    e.DisplayText = (e.RowHandle + 1).ToString();
                }
            }
        }
        private void gvDanhSachKhachHang_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            kh = (Khach_Hang)gvDanhSachKhachHang.GetRow(e.RowHandle);
            txtSoNha.Text = kh.KH_SoNha;
            cbbTTLoaiKH.EditValue = kh.KH_LID;
            txtSoLuong.Text = kh.KH_SoLuong.ToString();
            txtHoTen.Text = kh.KH_Ten;
            txtDienThoai.Text = kh.KH_DienThoai;
            cbbKyHan.EditValue = kh.KH_KHNID;
            cbbTrangThai.EditValue = kh.KH_TTHDID;
            cbbNhanVien.EditValue = kh.KH_NVID;
            txtMaKhachHang.Text = kh.KH_MaKH;

            btLuu.Text = "Lưu";
            btXoa.Enabled = true;
            them = false;
        }
        private void txtMaKhachHang_EditValueChanged(object sender, EventArgs e)
        {
            TestMaKhachHang();
        }

        #endregion

        private void FormQuanLyKhachHang_Load(object sender, EventArgs e)
        {
            FillSource2LookUpEdit(cbbQuanHuyen, QuanHuyen(), "QH_Ten", "QH_ID");
            FillSource2LookUpEdit(cbbTuyenDuong, Duong(), "D_Ten", "D_ID");
            FillSource2LookUpEdit(cbbTTLoaiKH, LoaiKhachHang(), "L_TenLoai", "L_ID");
            FillSource2LookUpEdit(cbbKyHan, KyHanNop(), "KHN_Ten", "KHN_ID");
            FillSource2LookUpEdit(cbbTrangThai, TrangThai(), "TTHD_TenTT", "TTHD_ID");
            FillSource2LookUpEdit(cbbNhanVien, NhanVien(), "NV_Ten", "NV_ID");

            groupControl1.Focus();
            cbbQuanHuyen.Focus();
            btXoa.Enabled = false;
        }

        private void btXem_Click(object sender, EventArgs e)
        {
            if (TestDiaChi())
            {
                GridViewDSKH_Load();
                ClearThongTin();    
            }
        }

        private void btLuu_Click(object sender, EventArgs e)
        {
            if (TestDiaChi() && TestThongTinCaNhan())
            {
                if (!TestMaKhachHang())
                {
                    XtraMessageBox.Show("Mã khách hàng không hợp lệ. Vui lòng nhấn F5 để tạo lại mã khách hàng.", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    if (them)
                    {
                        //Sự kiện thêm
                        kh = new Khach_Hang();

                        //set new
                        #region
                        kh.KH_MaKH = txtMaKhachHang.Text;

                        if (cbbKhuVuc.EditValue != null)
                        {
                            Khu_Vuc kv = (from k in dc.Khu_Vucs where k.KV_ID == (int)cbbKhuVuc.EditValue select k).Single();
                            kh.Khu_Vuc = kv;
                        }

                        if (cbbTuyenDuong.EditValue != null)
                        {
                            Duong duong = (from d in dc.Duongs where d.D_ID == (int)cbbTuyenDuong.EditValue select d).Single();
                            kh.Duong = duong;
                        }

                        kh.KH_SoNha = txtSoNha.Text;
                        kh.KH_Ten = txtHoTen.Text;

                        if (cbbTTLoaiKH.EditValue != null)
                        {
                            Loai_Khach_Hang loai = (from l in dc.Loai_Khach_Hangs where l.L_ID == (int)cbbTTLoaiKH.EditValue select l).Single();
                            kh.Loai_Khach_Hang = loai;
                        }
                        kh.KH_SoLuong = int.Parse(txtSoLuong.Text);

                        if (cbbKyHan.EditValue != null)
                        {
                            Ky_Han_Nop kyhan = (from k in dc.Ky_Han_Nops where k.KHN_ID == (int)cbbKyHan.EditValue select k).Single();
                            kh.Ky_Han_Nop = kyhan;
                        }

                        if (cbbTrangThai.EditValue != null)
                        {
                            Trang_Thai_Hoat_Dong tt = (from t in dc.Trang_Thai_Hoat_Dongs where t.TTHD_ID == (int)cbbTrangThai.EditValue select t).Single();
                            kh.Trang_Thai_Hoat_Dong = tt;
                        }

                        kh.KH_DienThoai = txtDienThoai.Text;

                        if (cbbNhanVien.EditValue != null)
                        {
                            Nhan_Vien nv = (from n in dc.Nhan_Viens where n.NV_ID == (int)cbbNhanVien.EditValue select n).Single();
                            kh.Nhan_Vien = nv;
                        }
                        #endregion

                        var Temp = from t in dc.Khach_Hangs where t.KH_MaKH == kh.KH_MaKH select t;
                        if (Temp.Count() > 0)
                        {
                            XtraMessageBox.Show("Mã khách hàng đã tồn tại. Vui lòng kiểm lại địa chỉ hoặc số nhà khách hàng.", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            dxErrorSoNha.SetError(txtSoNha, "Vui lòng kiểm tra lại số nhà.");
                        }
                        else
                        {
                            dc.Khach_Hangs.InsertOnSubmit(kh);
                            try
                            {
                                dc.SubmitChanges();
                                btBoQua_Click(null, EventArgs.Empty);
                            }
                            catch (Exception)
                            {
                                throw;
                            }
                        }
                    }
                    else
                    {
                        //Sự kiện lưu

                        #region
                        kh.KH_MaKH = txtMaKhachHang.Text;

                        if (cbbKhuVuc.EditValue != null)
                        {
                            Khu_Vuc kv = (from k in dc.Khu_Vucs where k.KV_ID == (int)cbbKhuVuc.EditValue select k).Single();
                            kh.Khu_Vuc = kv;
                        }

                        if (cbbTuyenDuong.EditValue != null)
                        {
                            Duong duong = (from d in dc.Duongs where d.D_ID == (int)cbbTuyenDuong.EditValue select d).Single();
                            kh.Duong = duong;
                        }

                        kh.KH_SoNha = txtSoNha.Text;
                        kh.KH_Ten = txtHoTen.Text;

                        if (cbbTTLoaiKH.EditValue != null)
                        {
                            Loai_Khach_Hang loai = (from l in dc.Loai_Khach_Hangs where l.L_ID == (int)cbbTTLoaiKH.EditValue select l).Single();
                            kh.Loai_Khach_Hang = loai;
                        }
                        kh.KH_SoLuong = int.Parse(txtSoLuong.Text);

                        if (cbbKyHan.EditValue != null)
                        {
                            Ky_Han_Nop kyhan = (from k in dc.Ky_Han_Nops where k.KHN_ID == (int)cbbKyHan.EditValue select k).Single();
                            kh.Ky_Han_Nop = kyhan;
                        }

                        if (cbbTrangThai.EditValue != null)
                        {
                            Trang_Thai_Hoat_Dong tt = (from t in dc.Trang_Thai_Hoat_Dongs where t.TTHD_ID == (int)cbbTrangThai.EditValue select t).Single();
                            kh.Trang_Thai_Hoat_Dong = tt;
                        }

                        kh.KH_DienThoai = txtDienThoai.Text;

                        if (cbbNhanVien.EditValue != null)
                        {
                            Nhan_Vien nv = (from n in dc.Nhan_Viens where n.NV_ID == (int)cbbNhanVien.EditValue select n).Single();
                            kh.Nhan_Vien = nv;
                        }
                        else
                        {
                            kh.Nhan_Vien = null;
                        }
                        #endregion

                        var temp = from t in dc.Khach_Hangs where t.KH_MaKH == kh.KH_MaKH && t.KH_ID != kh.KH_ID select t;
                        if (temp.Count() > 0)
                        {
                            XtraMessageBox.Show("Mã khách hàng đã tồn tại. Vui lòng kiểm lại địa chỉ hoặc số nhà khách hàng.", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            dxErrorSoNha.SetError(txtSoNha, "Vui lòng kiểm tra lại số nhà.");
                        }
                        else
                        {
                            try
                            {
                                dc.SubmitChanges();
                                btBoQua_Click(null, EventArgs.Empty);
                            }
                            catch (Exception ex)
                            {
                                if (ex.Message.Contains("Row not found or changed"))
                                {
                                    dc.Refresh( System.Data.Linq.RefreshMode.OverwriteCurrentValues ,kh);
                                    dc.SubmitChanges();
                                }
                                else
                                {
                                    throw;
                                }
                            }
                        }
                    }
                }
            }
        }

        private void btXoa_Click(object sender, EventArgs e)
        {
            DialogResult dr = new DialogResult();
            dr = XtraMessageBox.Show("Bạn có chắc xóa không?", "Xác nhận", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dr == DialogResult.Yes)
            {
                try
                {
                    if (kh.Doanh_Bo_Thangs.Count > 0)
                    {
                        XtraMessageBox.Show("Không thể xóa!\nDữ liệu đang được sử dụng.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    else
                    {
                        dc.Khach_Hangs.DeleteOnSubmit(kh);
                        dc.SubmitChanges();
                        XtraMessageBox.Show("Xóa thành công!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        btXem_Click(null, EventArgs.Empty);
                    }
                }
                catch (Exception)
                {
                    throw;
                }    
            }
        }
                
        private void btBoQua_Click(object sender, EventArgs e)
        {
            ClearThongTin();
            GridViewDSKH_Load();
            btXoa.Enabled = false;

            //cbbQuanHuyen.Enabled = true;
            //cbbQuanHuyen.EditValue = null;

            //cbbPhuongXa.Enabled = true;
            //cbbPhuongXa.EditValue = null;

            //cbbKhuVuc.Enabled = true;
            //cbbKhuVuc.EditValue = null;

            //cbbTuyenDuong.Enabled = true;
            //cbbTuyenDuong.EditValue = null;

            //gcDanhSachKhachHang.DataSource = null;

            btLuu.Text = "Thêm";
            them = true;
        }

        
       

    
    }
}